/**
 * Project Store
 * 负责管理project相关的状态和数据处理
 */

import { observable, action, computed  } from 'mobx-miniprogram';
import dateHelper from '../../../store/helpers/date_helper';

// 定义项目缓存Key
const PROJECT_LIST_CACHE_KEY = 'PROJECT_LIST_CACHE_KEY';
const PROJECT_DETAIL_CACHE_KEY = 'PROJECT_DETAIL_CACHE_KEY_';
const CACHE_EXPIRE_TIME = 30 * 60 * 1000; // 30分钟

// 项目模块Store
export const projectStore = observable({
  // 项目列表
  projectList: [],
  
  // 当前项目详情
  currentProject: null,
  
  // 列表状态
  listStatus: {
    loading: false,
    error: null,
    lastUpdateTime: null,
    hasMore: true,
    page: 1,
    size: 20
  },
  
  // 详情状态
  detailStatus: {
    loading: false,
    error: null,
    projectId: ''
  },
  
  // 搜索条件
  searchCondition: {
    search: '',
    sortType: 'time', // time, hot
    cateId: -1,
    status: -1, 
    activeStatus: -1
  },
  
  // 统计数据
  statistics: {
    total: 0,
    byStatus: {},
    byCategory: {}
  },
  
  // 获取项目类别列表
  get cateList() {
    return [
      { label: '全部', value: -1 },
      { label: '产品研发', value: 0 },
      { label: '技术研究', value: 1 },
      { label: '平台建设', value: 2 },
      { label: '工具开发', value: 3 },
      { label: '其他', value: 4 }
    ];
  },
  
  // 获取项目状态列表
  get statusList() {
    return [
      { label: '全部', value: -1 },
      { label: '进行中', value: 0 },
      { label: '已完成', value: 1 },
      { label: '已取消', value: 2 }
    ];
  },
  
  // 获取项目激活状态列表
  get activeStatusList() {
    return [
      { label: '全部', value: -1 },
      { label: '未激活', value: 0 },
      { label: '已激活', value: 1 }
    ];
  },
  
  // 计算属性：获取最近更新的项目
  get recentProjects() {
    // 使用Day.js处理日期排序
    return [...this.projectList]
      .sort((a, b) => dateHelper.dayjs(b.EDIT_TIME).valueOf() - dateHelper.dayjs(a.EDIT_TIME).valueOf())
      .slice(0, 5);
  },
  
  // 计算属性：按类别分组的项目
  get projectsByCategory() {
    const result = {};
    
    // 初始化类别组
    this.cateList.forEach(cate => {
      if (cate.value !== -1) {
        result[cate.value] = [];
      }
    });
    
    // 分类项目
    this.projectList.forEach(project => {
      if (result[project.PROJECT_CATE] !== undefined) {
        result[project.PROJECT_CATE].push(project);
      }
    });
    
    return result;
  },
  
  // 计算属性：即将到期的项目
  get upcomingDeadlineProjects() {
    const now = dateHelper.now();
    const oneWeekLater = dateHelper.add(now, 7, 'day');
    
    return this.projectList
      .filter(project => {
        if (project.PROJECT_STATUS !== 0) return false; // 只关注进行中的项目
        
        // 判断截止日期是否在一周内
        return dateHelper.isBetween(
          project.PROJECT_DEADLINE,
          now,
          oneWeekLater
        );
      })
      .sort((a, b) => dateHelper.dayjs(a.PROJECT_DEADLINE).valueOf() - dateHelper.dayjs(b.PROJECT_DEADLINE).valueOf());
  },
  
  // 计算属性：获取项目状态文本
  getProjectStatusText(project) {
    if (!project) return '';
    
    const statusMap = {
      0: '进行中',
      1: '已完成',
      2: '已取消'
    };
    
    return statusMap[project.PROJECT_STATUS] || '未知状态';
  },
  
  // 计算属性：获取格式化的项目截止日期
  getProjectDeadlineFormatted(project) {
    if (!project || !project.PROJECT_DEADLINE) return '';
    return dateHelper.formatDate(project.PROJECT_DEADLINE);
  },
  
  // 计算属性：获取友好的项目创建时间
  getProjectCreateTimeFriendly(project) {
    if (!project || !project.ADD_TIME) return '';
    return dateHelper.formatFriendly(project.ADD_TIME);
  },
  
  // 计算属性：获取项目截止状态 (已过期、即将到期、正常)
  getProjectDeadlineStatus(project) {
    if (!project || !project.PROJECT_DEADLINE) return 'normal';
    
    const now = dateHelper.now();
    const deadline = project.PROJECT_DEADLINE;
    
    if (deadline < now) return 'expired';
    
    const daysLeft = dateHelper.diff(deadline, now, 'day');
    if (daysLeft <= 7) return 'warning';
    
    return 'normal';
  },
  
  // Action: 初始化列表
  initList: action(function() {
    // 使用内置缓存方法
    try {
      const cache = wx.getStorageSync(PROJECT_LIST_CACHE_KEY);
      if (cache) {
        this.projectList = cache.list || [];
        this.statistics = cache.statistics || {
          total: 0,
          byStatus: {},
          byCategory: {}
        };
        this.listStatus.lastUpdateTime = cache.time;
        
        // 检查缓存是否需要刷新
        const now = dateHelper.now();
        if (now - cache.time > CACHE_EXPIRE_TIME) { // 缓存30分钟
          this.refreshList();
        }
      } else {
        this.refreshList();
      }
    } catch (e) {
      console.error('Failed to init project list from cache', e);
      this.refreshList();
    }
  }),
  
  // Action: 刷新列表
  refreshList: action(async function() {
    try {
      this.listStatus.loading = true;
      this.listStatus.error = null;
      this.listStatus.page = 1;
      this.listStatus.hasMore = true;
      
      await this.loadList(true);
    } catch (e) {
      console.error('Failed to refresh project list', e);
      this.listStatus.error = e.message || '加载失败';
    } finally {
      this.listStatus.loading = false;
    }
  }),
  
  // Action: 加载列表
  loadList: action(async function(refresh = false) {
    try {
      if (this.listStatus.loading) return;
      if (!this.listStatus.hasMore && !refresh) return;
      
      this.listStatus.loading = true;
      this.listStatus.error = null;
      
      // 模拟从服务器加载数据
      const mockData = {
        data: [
          {
            _id: '1',
            PROJECT_TITLE: '示例项目1',
            PROJECT_CODE: 'PRJ001',
            PROJECT_MANAGER_NAME: '张三',
            ADD_TIME: dateHelper.now(),
            PROJECT_DEADLINE: dateHelper.add(dayjs(), 30, 'day').valueOf(),
            PROJECT_STATUS: 0,
            PROJECT_CATE: 0,
            PROJECT_PROGRESS: 30
          },
          {
            _id: '2',
            PROJECT_TITLE: '示例项目2',
            PROJECT_CODE: 'PRJ002',
            PROJECT_MANAGER_NAME: '李四',
            ADD_TIME: dateHelper.subtract(dayjs(), 10, 'day').valueOf(),
            PROJECT_DEADLINE: dateHelper.add(dayjs(), 60, 'day').valueOf(),
            PROJECT_STATUS: 1,
            PROJECT_CATE: 1,
            PROJECT_PROGRESS: 100
          }
        ],
        statistics: {
          total: 2,
          byStatus: {0: 1, 1: 1},
          byCategory: {0: 1, 1: 1}
        }
      };
      
      const result = mockData;
      
      if (result && result.data) {
        const list = result.data;
        
        if (refresh) {
          this.projectList = list;
        } else {
          this.projectList = this.projectList.concat(list);
        }
        
        // 更新分页状态
        this.listStatus.hasMore = false; // 模拟数据没有更多了
        this.listStatus.page = refresh ? 2 : this.listStatus.page + 1;
        this.listStatus.lastUpdateTime = dateHelper.now();
        
        // 更新统计数据
        if (result.statistics) {
          this.statistics = result.statistics;
        }
        
        // 存入缓存
        this._saveListCache();
      }
    } catch (e) {
      console.error('Failed to load project list', e);
      this.listStatus.error = e.message || '加载失败';
    } finally {
      this.listStatus.loading = false;
    }
  }),
  
  // Action: 设置搜索条件
  setSearchCondition: action(function(condition) {
    this.searchCondition = {...this.searchCondition, ...condition};
  }),
  
  // Action: 清空搜索条件
  clearSearchCondition: action(function() {
    this.searchCondition = {
      search: '',
      sortType: 'time',
      cateId: -1,
      status: -1,
      activeStatus: -1
    };
  }),
  
  // Action: 加载项目详情
  loadProjectDetail: action(async function(id, refresh = false) {
    try {
      if (this.detailStatus.loading) return;
      
      this.detailStatus.loading = true;
      this.detailStatus.error = null;
      this.detailStatus.projectId = id;
      
      // 先尝试从缓存获取
      if (!refresh) {
        const cacheKey = PROJECT_DETAIL_CACHE_KEY + id;
        const cache = wx.getStorageSync(cacheKey);
        
        if (cache && cache.detail) {
          const now = dateHelper.now();
          // 检查缓存是否在有效期内
          if (now - cache.time < CACHE_EXPIRE_TIME) {
            this.currentProject = cache.detail;
            this.detailStatus.loading = false;
            return this.currentProject;
          }
        }
      }
      
      // 模拟从服务器加载数据
      // 实际项目中应该调用云函数或API获取详情
      const mockDetail = this.projectList.find(p => p._id === id) || {
        _id: id,
        PROJECT_TITLE: '详情项目',
        PROJECT_CODE: 'PRJ' + id,
        PROJECT_MANAGER_NAME: '王五',
        ADD_TIME: dateHelper.now(),
        EDIT_TIME: dateHelper.now(),
        PROJECT_DEADLINE: dateHelper.add(dayjs(), 45, 'day').valueOf(),
        PROJECT_STATUS: 0,
        PROJECT_CATE: 2,
        PROJECT_PROGRESS: 50,
        PROJECT_DESC: '这是一个示例项目描述',
        PROJECT_MEMBERS: [
          { id: 'u1', name: '成员1' },
          { id: 'u2', name: '成员2' }
        ],
        PROJECT_TASKS: [
          { 
            id: 't1', 
            title: '任务1', 
            status: 0, 
            time: dateHelper.now() 
          },
          { 
            id: 't2', 
            title: '任务2', 
            status: 1, 
            time: dateHelper.now() 
          }
        ]
      };
      
      // 更新状态
      this.currentProject = mockDetail;
      
      // 存入缓存
      const cacheData = {
        detail: mockDetail,
        time: dateHelper.now()
      };
      wx.setStorageSync(PROJECT_DETAIL_CACHE_KEY + id, cacheData);
      
      return this.currentProject;
    } catch (e) {
      console.error('Failed to load project detail', e);
      this.detailStatus.error = e.message || '加载详情失败';
    } finally {
      this.detailStatus.loading = false;
    }
  }),
  
  // Action: 更新项目任务
  updateProjectTask: action(function(projectId, taskId, data) {
    if (!this.currentProject || this.currentProject._id !== projectId) return;
    
    const taskIndex = this.currentProject.PROJECT_TASKS.findIndex(t => t.id === taskId);
    if (taskIndex === -1) return;
    
    // 更新任务数据
    this.currentProject.PROJECT_TASKS[taskIndex] = {
      ...this.currentProject.PROJECT_TASKS[taskIndex],
      ...data,
      time: dateHelper.now() // 更新时间
    };
    
    // 更新缓存
    const cacheKey = PROJECT_DETAIL_CACHE_KEY + projectId;
    const cacheData = {
      detail: this.currentProject,
      time: dateHelper.now()
    };
    wx.setStorageSync(cacheKey, cacheData);
  }),
  
  // Action: 添加项目任务
  addProjectTask: action(function(projectId, taskData) {
    if (!this.currentProject || this.currentProject._id !== projectId) return;
    
    // 创建新任务
    const newTask = {
      id: 't' + dateHelper.now(),
      title: taskData.title,
      status: 0,
      time: dateHelper.now(),
      ...taskData
    };
    
    // 添加到任务列表
    this.currentProject.PROJECT_TASKS = [
      ...this.currentProject.PROJECT_TASKS,
      newTask
    ];
    
    // 更新缓存
    const cacheKey = PROJECT_DETAIL_CACHE_KEY + projectId;
    const cacheData = {
      detail: this.currentProject,
      time: dateHelper.now()
    };
    wx.setStorageSync(cacheKey, cacheData);
    
    return newTask;
  }),
  
  // 内部方法：保存列表缓存
  _saveListCache: function() {
    try {
      const cacheData = {
        list: this.projectList,
        statistics: this.statistics,
        time: this.listStatus.lastUpdateTime
      };
      wx.setStorageSync(PROJECT_LIST_CACHE_KEY, cacheData);
    } catch (e) {
      console.error('Failed to save project list cache', e);
    }
  }
}); 